package com.zj.leetcode.medium;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @program: algorithm
 * @description:
 * 451. 根据字符出现频率排序
 * @author: Zhang Bo
 * @create: 2022-01-10 16:41
 **/
public class SortCharactersByFrequency {
    public static void main(String[] args) {
//        String s = "tree";
        String s = "cccaaadaf";
        Solution solution = new SortCharactersByFrequency().new Solution();
        System.out.println(solution.frequencySort(s));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String frequencySort(String s) {
            HashMap<Character, Integer> map = new HashMap<>();

            for (int i = 0; i < s.length(); i++) {
                map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
            }

            Stream<Map.Entry<Character, Integer>> sort =
                    map.entrySet()
                            .stream()
                            .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()));
            StringBuilder ret = new StringBuilder();
            sort.forEach(entry -> {
                for (int i = 0; i < entry.getValue(); i++) {
                    ret.append(entry.getKey());
                }
            });

            return ret.toString();
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
